package main

import (
	"fmt"
	"os"
)

// UtilizeWriter create post install script
type UtilizeWriter struct {
	fd *os.File
}

// NewUtilizeWriter todo
func NewUtilizeWriter(name string) (*UtilizeWriter, error) {
	var err error
	var uw UtilizeWriter
	if uw.fd, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755); err != nil {
		return nil, err
	}
	return &uw, nil
}

// WriteBase todo
func (uw *UtilizeWriter) WriteBase() error {
	if _, err := uw.fd.WriteString(PostInstallScript); err != nil {
		return err
	}
	return nil
}

// AddTarget todo
func (uw *UtilizeWriter) AddTarget(relname string) error {
	fmt.Fprintf(uw.fd, "echo -e \"install target \\x1b[32m$TOPLEVEL/%s\\x1b[0m\"\nbali_apply_target \"$TOPLEVEL/%s\"\n", relname, relname)
	return nil
}

// AddProfile todo
func (uw *UtilizeWriter) AddProfile(relname string) error {
	fmt.Fprintf(uw.fd, "echo -e \"apply config \\x1b[32m$TOPLEVEL/%s\\x1b[0m\"\nbali_apply_config \"$TOPLEVEL/%s\"\n", relname, relname)
	return nil
}

// Close todo
func (uw *UtilizeWriter) Close() error {
	fmt.Fprintf(uw.fd, "rm \"$TOPLEVEL/post_install.sh\"\n")
	return uw.fd.Close()
}
